require( "gip")
require( "util")

local genPath
local failedCount
local successCount

function transCallback( filename)
    filename = string.lower(filename)
    local _, imageFileName = splitPath( filename)
    local dotPos = string.find( imageFileName, ".png", #imageFileName - 4)
    if dotPos == nil then
        return
    end
    
    image = gip.load( filename)
    if image == nil then
        print( "\n")
        print( "load image failed: " .. filename)
        failedCount = failedCount + 1
        return
    end
    io.write( ".")
        
    local dstPath = genPath .. string.sub( imageFileName, 1, #imageFileName - 4)
    local iw = image.getW()
    local ih = image.getH()
    
    local r = 0
    local c = 0
    local x, y, w, h
    for y = 0, ih - 1, 256 do
        c = 0
        if y + 256 > ih then
            h = ih - y
        else
            h = 256
        end
        
        for x = 0, iw - 1, 256 do
            if x + 256 > iw then
                w = iw - x
            else
                w = 256
            end
            
            --io.write( "-")
            --print(x, y, w, h)
            local subImage = image.cut( x, y, w, h)
            local name = string.format( "%s/%d_%d.jpg", dstPath, r, c)
            local ret = subImage.save( name)
            subImage = nil
            if not ret then
                print( "save" .. name .. "failed!")
            end
            
            c = c + 1
        end
        r = r + 1
    end
    
    local descFileName = string.format( "%s/desc.txt", dstPath)
    local descFile, errMsg = io.open( descFileName, "w")
    if descFile then
        local txt = string.format( "width %d\r\nheight %d\r\nrow %d\r\ncol %d",
            iw, ih, r, c)
        descFile:write( txt)
        descFile:close()
    else
        local s = string.format("write desc file failed. [%s: %s]\n", descFileName, errMsg);
        print( s)
    end
    
    image = nil    
end

function genMap( srcPath, dstPath)
    genPath = dstPath
    failedCount = 0
    successCount = 0
    
    gip.setJpgQuality( 75)
    gip.transDir( srcPath, transCallback, false)
    
    
    if failedCount == 0 then
        print( "\nIt's all OK!")
    else
        local s = string.format( "\nsuccess: %d, failed: %d",
            successCount, failedCount)
        print( s)
    end
end

--genMap( "D:\\gems\\map\\src", "D:\\gems\\map\\")
return function()
    gip.init()
    genMap( "/export/arts/pak/map_png", "/export/arts/pak/map_splited/")
    gip.deInit()
end

